import { Injectable } from '@angular/core';
import { QueueingSubject } from 'queueing-subject';
import { Observable } from 'rxjs/Observable';
import websocketConnect from 'rxjs-websockets';
import 'rxjs/add/operator/share';
import {TokenService} from '@core/net/token/token.service';

@Injectable()
export class ServerSocket {
    private inputStream: QueueingSubject<string>
    public messages: Observable<string>
    constructor(private token: TokenService) { }
    public connect() {

//139.196.189.173:8089
        // Using share() causes a single websocket to be created when the first
        // observer subscribes. This socket is shared with subsequent observers
        // and closed when the observer count falls to zero.
        if(!this.token.data.access_token){
           return
        }
        this.messages = websocketConnect(
            // 弘毅重远
            //'ws://39.104.122.0:8280/VisualizationMgt/websocket.do?token='+this.token.data.access_token+"&type=pc",
            // 麦尼哲
            //'ws://139.196.189.173:8089/VisualizationMgt/websocket.do?token='+this.token.data.access_token+"&type=pc",
            // 田洪洋
            //'ws://192.168.0.19/api/Socket/websocket?token='+this.token.data.access_token+"&type=pc",
            // 铝箔
             'ws://192.168.0.19/api/Socket/websocket?token='+this.token.data.access_token+"&type=pc",
            // 测试

            this.inputStream = new QueueingSubject<string>()
        ).messages.share();
    }
    public reconnect() {
        if(!this.token.data.access_token){
            return
        }
        this.messages=null;
        this.messages = websocketConnect(
            'ws://192.168.0.19/api/Socket/websocket?token='+this.token.data.access_token+"&type=pc",
            this.inputStream = new QueueingSubject<string>()
        ).messages.share()
    }

    public send(message: string):void {
        // If the websocket is not connected then the QueueingSubject will ensure
        // that messages are queued and delivered when the websocket reconnects.
        // A regular Subject can be used to discard messages sent when the websocket
        // is disconnected.
        this.inputStream.next(message)
    }
}
